import TIM from 'tim-wx-sdk';
import area from "@/components/citySelect/city-data/area.js";
import city from "@/components/citySelect/city-data/city.js";
import province from "@/components/citySelect/city-data/province.js";
import API from "@/common/api.js";
import {
	genTestUserSig
} from '@/sdk/timWx/GenerateTestUserSig.js';
import Request from "@/sdk/pocky-request/index.js"; //引入
export default {
	/**
	 * @description 根据经纬度获取亮点之间的距离
	 * @param {Float} lat1 目标点经度
	 * @param {Float} lng1	目标点纬度
	 * @param {Float} lat2	当前定位经度
	 * @param {Float} lng2	当前定位纬度
	 */
	getDis(lat1,lng1,lat2,lng2){
		let EARTH_RADIUS = 6378137.0; //单位M
		let PI = Math.PI;
		
		function getRad(d) {
			return d * PI / 180.0;
		}
		
		var radLat1 = getRad(lat1);
		var radLat2 = getRad(lat2);
		
		var a = radLat1 - radLat2;
		var b = getRad(lng1) - getRad(lng2);
		
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
			Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000.0;
		
		if (s > 1000) {
			s = (s / 1000).toFixed(2) + 'km'
		} else {
			s = s.toFixed(2) + '米'
		}
		return s;
	},
	
	getTm(_time) {
		// console.log(_time);

		var theTime = parseInt(_time); // 秒
		var middle = 0; // 分
		var hour = 0; // 小时

		if (theTime > 60) {
			middle = parseInt(theTime / 60);
			theTime = parseInt(theTime % 60);
			if (middle > 60) {
				hour = parseInt(middle / 60);
				middle = parseInt(middle % 60);
			}
		}
		var result = "" + parseInt(theTime) + "秒";
		if (middle > 0) {
			result = "" + parseInt(middle) + "分钟" + result;
		}
		if (hour > 0) {
			result = "" + parseInt(hour) + "小时" + result;
		}
		return result;

	},
	isStart(_str){
		let _now=new Date().getTime();
		let _year=parseInt( _str.split(' ')[0].split('-')[0]);
		let _month=parseInt(_str.split(' ')[0].split('-')[1])-1;
		let _day=parseInt(_str.split(' ')[0].split('-')[2]);
		let _hour=parseInt(_str.split(' ')[1].split(':')[0]);
		let _min=parseInt(_str.split(' ')[1].split(':')[1]);
		let _sec=parseInt(_str.split(' ')[1].split(':')[2]);
		let _n=new Date();
		_n.setFullYear(_year,_month,_day)
		_n.setHours(_hour);
		_n.setMinutes(_min);
		_n.setSeconds(_sec);
		console.log(_n.toString());
		let _nTim=_n.getTime();
		return _now>_nTim;
	},
	/**
	 * @description 将对象转化为URL后的参数，注意只能转化单层对象
	 * @param {Object} params 
	 * @return {String} 转化后的字符串
	 * @example paramsURL({id:123,name:'张三'})   =>  id=123&name=张三
	 */
	paramsURL(params) {
		let newParams = params;
		let newURL = '';


		for (const [key, val] of Object.entries(newParams || {})) {
			newURL += `${key}=${val}&`;
		}

		return newURL.substring(0, newURL.length - 1);
	},
	/**
	 * @description  带参url转换为object
	 * @param {Object} str  URL
	 * @return {Object}
	 */
	pramsUrlToObj(str) {
		let obj = {
			url: ''
		};
		let opt = {};
		if (str.split("?") < 1) {
			obj = {
				url: str
			}
		} else {
			var arr = str.split("?");
			obj = {
				url: arr[0]
			}
			if (arr[1]) {
				var arr2 = arr[1].split("&");
				for (var i = 0; i < arr2.length; i++) {
					var res = arr2[i].split("=");
					opt[res[0]] = res[1];
				}
			}
		}
		obj.opt = opt;
		return obj;
	},
	/**
	 * @description  字符串转对象
	 * @param {Object} str
	 */
	strToObj(str) {
		let opt = {};
		var arr2 = str.split("&");
		for (var i = 0; i < arr2.length; i++) {
			var res = arr2[i].split("=");
			opt[res[0]] = res[1];
		}
		return opt;
	},
	/**
	 * @description 通过页面名检查页面是否已经打开
	 * @param {Object} pageName
	 * @return {Number} 如果已经打开过,返回回退需要的back数
	 */
	checkPageOpendByName(pageName) {
		let lastOpenIndex = 0; //最后一次打开index
		let openCount = 0; //已打开的数量
		let pageArr = getCurrentPages(); //获取页面栈数组
		let firstOpendIndex = 0; //第一次打开index
		//遍历页面栈,获取最后一次打开同名的index和已打开同名页面的数量
		pageArr.forEach(function(v, i) {
			//数组中判断是否有此页面  注意这边用的是array.indexOf方法
			let opd = v.route.split('/').indexOf(pageName) > 0;
			if (opd) {
				lastOpenIndex = i;
				openCount++;
				if (firstOpendIndex == 0) {
					firstOpendIndex = i;
				}
			}
		});
		return {
			opendCount: openCount, //已打开页面数
			lastOpendIndex: lastOpenIndex, //最后一次打开index
			firstOpendIndex: firstOpendIndex, //第一次打开index
			backLastLength: pageArr.length - lastOpenIndex - 1,
			backFirstLength: pageArr.length - firstOpendIndex - 1,
			pageCount: pageArr.length
		}
	},
	

	/**
	 * @description 拨打电话,拨打前会检查权限
	 * @param {Object} tel
	 */
	callPhone(tel) {
		// #ifdef MP
		uni.makePhoneCall({
			phoneNumber: tel
		});
		// #endif
	},
	/**
	 * @description 通过经纬度坐标打开地图
	 * @param {Object} shopData 店铺经纬度坐标
	 */
	toMapBylng(shopData) {
		// #ifdef MP
		uni.openLocation({
			latitude: shopData.lati,
			longitude: shopData.longi,
			name: shopData.name,
			address: shopData.address,
			success: function() {
				console.log('success');
			}
		});
		// #endif
	},
	/**
	 * @description 通过areaid获取省市区
	 * @param {Object} _areaId
	 * 
	 */
	getSSQByAreaId(_areaId) {
		_areaId = _areaId.toString();
		let _ctIndex, _areaIndex, _shIndex;
		area.forEach((item, n) => {
			// console.log(item);
			item.forEach((i, m) => {
				// console.log(i);
				i.forEach((x, y) => {
					// console.log(x);
					if (x.value == _areaId) {
						// console.log(x);
						_ctIndex = m;
						_areaIndex = y;
						_shIndex = n;
					}
				})

			})
		})

		return [province[_shIndex].label, city[_shIndex][_ctIndex].label, area[_shIndex][_ctIndex][_areaIndex].label]
	},
	/**
	 * @description 下载文件
	 * @param {Object} fileUrl=[需要下载的文件url]
	 * @example  https://www.hawklu.com/testPage/ranking.apk
	 */
	downloadFile(fileUrl,_json) {
		let _this = this;
		return new Promise((resolve, reject) => {
			console.log(fileUrl);
			const downloadTask = uni.downloadFile({
				url: fileUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						console.log("文件下载成功，暂存地址:" + res.tempFilePath);
						resolve(res.tempFilePath);
	
					} else {
						uni.showModal({
							title: '更新失败',
							content: '安装包下载失败，请检查网络或重启应用试试',
							showCancel: false,
							cancelText: '',
							confirmText: '确定',
							success: res => {},
							fail: () => {},
							complete: () => {
								plus.runtime.quit();
							}
						});
						reject(res);
					}
				},
				fail: err => {
					uni.showModal({
						title: '更新失败',
						content: '安装包下载失败，请检查网络或重启应用试试',
						showCancel: false,
						cancelText: '',
						confirmText: '确定',
						success: res => {},
						fail: () => {},
						complete: () => {
							plus.runtime.quit();
						}
					});
				}
			});
	
			// 下载中处理
			downloadTask.onProgressUpdate((res) => {
				// uni.showLoading({
				// 	title: '正在下载中...'+res.progress+'%',
				// 	mask: false
				// });
				if(_json.type==2){
					uni.$emit("downing", res);
				}
				// console.log('下载进度' + res.progress);
				// console.log('已经下载的数据长度' + res.totalBytesWritten);
				// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
				// 测试条件，取消下载任务。
	
			});
		})
	
	},

}
